package com.zxt.redis.aspect;

import com.alibaba.fastjson.JSON;
import com.zxt.bean.ResultCode;
import com.zxt.bean.ServiceException;
import com.zxt.redis.annotation.CustomCache;
import com.zxt.redis.utils.RedisUtil;
import com.zxt.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * aop实现
 *
 * @author zxt
 */
@Aspect
@Component
public class CustomCacheHandler {
    private static final Logger log = LoggerFactory.getLogger(CustomCacheHandler.class);


    @Around("@annotation(customCache)")
    public Object around(ProceedingJoinPoint joinPoint, CustomCache customCache) throws Throwable {
        log.info("CustomCache -> 方法开始执行");
        String key = customCache.key();
        /**
         * 如果没有指定key，使用默认分配的
         */
        if (StringUtils.isEmpty(key)) {
            //如果没有指定key，以方法的包名+类目+方法名为key
            key = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        }

        /**
         * 取出当前方法的返回值类型，判断是否是List集合
         */
        Signature signature = joinPoint.getSignature();
        if (signature instanceof MethodSignature) {
            MethodSignature methodSignature = (MethodSignature) signature;
            // 被切的方法
            Method method = methodSignature.getMethod();
            //返回值类型是否是List集合
            if (method.getReturnType().isAssignableFrom(List.class)) {
                //找到返回值泛型
                Type genericType = method.getGenericReturnType();
                //类型转换
                ParameterizedType pt = (ParameterizedType) genericType;
                //得到泛型里的class类型对象  System.out.println(genericType);
                Class classType = (Class<?>) pt.getActualTypeArguments()[0];
                return doMethod(joinPoint, Boolean.TRUE, key, customCache.expirationTime(), classType, customCache.sync());
            } else {
                //Map,对象
                return doMethod(joinPoint, Boolean.FALSE, key, customCache.expirationTime(), method.getReturnType(), customCache.sync());
            }
        } else {
            return null;
        }
    }

    /**
     * 执行方法
     *
     * @param joinPoint
     * @param isList
     * @param key
     * @param expirationTime
     * @param classType
     * @return
     * @throws Throwable
     */
    private Object doMethod(ProceedingJoinPoint joinPoint, Boolean isList, String key, Integer expirationTime, Class classType, Boolean sync) throws Throwable {
        Object result = null;
        try {
            result = RedisUtil.get(key);
            if (Objects.nonNull(result)) {
                log.info("CustomCache -> 缓存生效 缓存返回");
                //走缓存
                RedisUtil.set(key, result.toString(), TimeUnit.MINUTES, expirationTime);
                if (isList) {
                    //缓存的是集合
                    result = JSON.parseArray(result.toString(), classType);
                } else {
                    //缓存的是对象
                    result = JSON.parseObject(result.toString(), classType);
                }
            } else {
                if (sync) {
                    result = syncCache(joinPoint, isList, key, expirationTime, classType);
                } else {
                    result = joinPoint.proceed();
                    RedisUtil.set(key, JSON.toJSONString(result), TimeUnit.MINUTES, expirationTime);
                    log.info("CustomCache -> 数据库返回 缓存成功");
                }
            }
        } catch (Exception e) {
            throw new ServiceException(ResultCode.COMMON_MESSAGE, e.getMessage());
        }
        return result;
    }

    private synchronized Object syncCache(ProceedingJoinPoint joinPoint, Boolean isList, String key, Integer expirationTime, Class classType) throws Throwable {
        Object result = null;
        result = RedisUtil.get(key);
        if (Objects.nonNull(result)) {
            log.info("CustomCache -> 缓存生效 缓存返回");
            //走缓存
            RedisUtil.set(key, result.toString(), TimeUnit.MINUTES, expirationTime);
            if (isList) {
                //缓存的是集合
                result = JSON.parseArray(result.toString(), classType);
            } else {
                //缓存的是对象
                result = JSON.parseObject(result.toString(), classType);
            }
        } else {
            log.info("CustomCache -> 数据库返回 缓存成功");
            result = joinPoint.proceed();
            RedisUtil.set(key, JSON.toJSONString(result), TimeUnit.MINUTES, expirationTime);
        }
        return result;
    }

}
